<template>
  <div class="app">
    <Sidebar />

    <main class="m-content">
      <div class="container">

        <section class="dialog-history-container">
          <div class="dialog-header">
            <h3 class="dialog-header-title">往期对话</h3>
            <div class="button-group">
              <el-button type="primary" icon="ChatRound" @click="createNewQADialog('智能问答', 1)">智能问答</el-button>
              <el-button type="warning" icon="EditPen" @click="createNewQADialog('难点定位', 2)">难点定位</el-button>
            </div>
          </div>


          <div class="dialog-list">
            <div class="chatpage-card-item" v-for="dialog in dialogs" :key="dialog.titleId" @click="changeDialog(dialog.titleId)">
              <div class="chatpage-item-content">
                <h3 class="chatpage-item-title">{{ dialog.title }}</h3>
                <div class="chatpage-item-icons">
                  <span class="star-icon">⭐</span>
                  <span class="delete-icon" @click="deleteDialog(dialog.titleId)">🗑️</span>
                </div>
              </div>
              <div class="chatpage-item-footer">
                <p class="item-date">{{ dialog.date }}</p>
                <span class="item-text">共{{ dialog.total }}条对话</span>
              </div>
            </div>
          </div>
        </section>

        <section class="chatbox-container">
          <div class="chat-header">
            <el-button icon="ArrowLeft" class="arrow-button" circle></el-button>
            <div class="chat-title">
              <h3>{{ title }}</h3>
              <p>共{{ length }}条对话</p>
            </div>
          </div>
          <section class="chatbox" id="scroll">
            <div
              :class="{
                'chat-content1': msg.role === 1,
                'chat-content0': msg.role === 0
              }" v-for="(msg, index) in messages" :key="index">
              <div class="chat-message">
                <div class="message-content" v-show="msg.role === 1">{{ msg.text }}</div>
                <div class="avatar" v-show="msg.role === 1">用户</div>
                <div class="avatar" v-show="msg.role === 0">小*</div>
                <div class="message-content" v-show="msg.role === 0">
                  <v-md-preview :text="msg.text"></v-md-preview>
                </div>
              </div>
            </div>
          </section>
          <div class="chat-input">
            <div class="related-topics">
              <h4>相关知识点</h4>
              <div class="topics">
                <el-button>鸡兔同笼问题</el-button>
                <el-button>鸡兔同笼问题</el-button>
                <el-button>鸡兔同笼问题</el-button>
              </div>
            </div>

            <div class="divider"></div>
            <div class="chatbox-button-group">
              <el-button circle icon="QuestionFilled"></el-button>
              <el-button circle icon="Tools"></el-button>
              <el-button circle icon="MagicStick"></el-button>
              <el-button circle icon="DeleteFilled"></el-button>
            </div>
            <div class="input-wrapper">
              <textarea
                v-model="input"
                placeholder="Shift+Enter换行，Enter发送"
                @keydown="keyDown"
                class="custom-textarea"
              ></textarea>
              <el-button
                type="primary"
                icon="Promotion"
                @click="sendMessage"
                class="send-button"
              >发送</el-button>
            </div>
          </div>
        </section>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import Sidebar from '@/components/Sidebar.vue';

import { onMounted, reactive, ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const input = ref('')
const title = ref('请开始一个新的对话')
const nowTitleId = ref(-1)
const length = ref(0)
const messages = reactive([])
const dialogs = reactive([])

const formatDate = (date: Date, format = 'yyyy-MM-dd HH:mm:ss'): string => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  const formatMap: { [key: string]: any } = {
    yyyy: year.toString(),
    MM: month.toString().padStart(2, '0'),
    dd: day.toString().padStart(2, '0'),
    HH: hour.toString().padStart(2, '0'),
    mm: minute.toString().padStart(2, '0'),
    ss: second.toString().padStart(2, '0')
  }
  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, (match) => formatMap[match])
}

const scrollToBottom = async () => {
  const div = document.getElementById('scroll');
  console.log('测试', div.scrollTop, div.scrollHeight)
  await div && (div.scrollTop = div.scrollHeight)
  console.log('测试', div.scrollTop, div.scrollHeight)
}

const getDialog = async () => {
  dialogs.splice(0)
  await axios.get('student/AI/allConversation')
    .then(res => {
      console.log(res.data.data)
      for (let i = 0; i < res.data.data.length; i ++) {
        dialogs.push({
          titleId: res.data.data[i].titleId,
          title: res.data.data[i].title,
          date: res.data.data[i].newTime,
          total: res.data.data[i].total
        })
      }
    })
}

onMounted( async () => {
  getDialog()
})

const createNewQADialog = async (createTitle: string, type: number) => {
  let tempTitleId = nowTitleId.value
  await axios.get('student/AI/nowTitleId')
    .then(res => {
      console.log(res.data.data)
      tempTitleId = res.data.data
      messages.splice(0)
    })
  console.log('tempTitleId', tempTitleId)
  if (tempTitleId != nowTitleId.value) {
    await axios.post('student/AI/createConversation', { titleId: tempTitleId, title: createTitle, moduleId: type })
      .then(res => {
        getDialog()
        nowTitleId.value = tempTitleId
        changeDialog(tempTitleId)
      })
  }
}

const deleteDialog = async (titleId) => {
  console.log('delete titleId', titleId)
  await axios.get('student/AI/deleteConversation?titleId=' + titleId)
    .then(res => {
      console.log(res)
      getDialog()
    })
}

const changeDialog = async (titleId) => {
  console.log('titleId', titleId)
  nowTitleId.value = titleId
  messages.splice(0)
  await axios.get('student/AI/onlyConversation?titleId=' + titleId)
    .then(res => {
      console.log(res)
      title.value = res.data.data.title
      length.value = res.data.data.onlyConversationVOList.length
      for (let i = res.data.data.onlyConversationVOList.length - 1; i >= 0; i --) {
        messages.push({
          text: res.data.data.onlyConversationVOList[i].content,
          role: res.data.data.onlyConversationVOList[i].role,
          time: res.data.data.onlyConversationVOList[i].createTime
        })
      }
    })
  scrollToBottom()
}

const tempInput = ref('');

const sendMessage = async () => {
  if (nowTitleId.value === -1) {
    ElMessage({
      message: '请选择一个对话或者创建一个对话',
      type: 'warning'
    })
    return
  }
  if (input.value.trim()) {
    messages.push({
      text: input.value,
      role: 1,
      time: formatDate(new Date(), "yyyy.MM.dd HH:mm:ss")
    }); // 将用户消息添加到消息数组
    tempInput.value = input.value;
    input.value = '';
    messages.push({
      text: '...',
      role: 0,
      time: formatDate(new Date(), "yyyy.MM.dd HH:mm:ss")
    })
    scrollToBottom();
    await axios.post('student/AI/receive', {
      titleId: nowTitleId.value,
      content: tempInput.value
    })
      .then(res => {
        messages.pop();
        messages.push({
          text: res.data.data,
          role: 0,
          time: formatDate(new Date(), "yyyy.MM.dd HH:mm:ss")
        })
        for (let i = 0; i < dialogs.length; i ++) {
          if (dialogs[i].titleId === nowTitleId.value) {
            dialogs[i].total = dialogs[i].total + 2
          }
        }
      })
    scrollToBottom();
    console.log(messages)
  }
}

const keyDown = (e) => {
  if (!e.shiftKey && e.keyCode == 13) {
    e.cancelBubble = true; //ie阻止冒泡行为
    e.stopPropagation();//Firefox阻止冒泡行为
    e.preventDefault(); //取消事件的默认动作*换行
    //以下处理发送消息代码
    sendMessage();
  }
}

</script>

<style>
.app {
  display: flex;
  height: 100vh;
}
.m-content {
  flex: 1;
  display: flex;
  padding: 0;
  background-color: #ffffff;
}
.container {
  display: flex;
  width: 100%;
}
.chat-header {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  background-color: #fff;
  border-bottom: 1px solid #eaeaea;
}

.chat-title {
  display: flex;
  flex-direction: column;
}

.chat-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.chat-title p {
  margin: 0;
  font-size: 14px;
  color: #999;
}

.dialog-history-container {
  width: 400px;
  margin-right: 0;
  background-color: #f6fbff;
  padding: 0 0 0 10px;
  border-radius: 8px;
}
.dialog-header {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  color: #409eff;
  font-size: 23px;
}

.dialog-header-title {
  align-self: flex-start;
  padding-left: 20px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.button-group button {
  padding: 5px;
  height: 50px;
  width: 135px;
  font-size: 20px;
  font-weight: bold;
}

.dialog-list {
  height: 750px;
  display: flex;
  flex-direction: column;
  overflow-y: auto; /* 设置纵向滚动 */
}
.chatpage-card-item {
  display: flex;
  flex-direction: column;
  padding: 15px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 25px;
  transition: transform 0.2s;
  cursor: pointer;
  height: 75px;
  width: 350px;
}
.chatpage-card-item:hover {
  transform: translateY(-2px);
}
.chatpage-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chatpage-item-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}
.item-date {
  font-size: 14px;
  color: #666;
}
.chatpage-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chatpage-item-icons {
  display: flex;
  gap: 10px;
}
.star-icon {
  color: #ffc107;
  cursor: pointer;
}
.delete-icon {
  color: #dc3545;
  cursor: pointer;
}
.chatbox-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.chat-header {
  padding: 10px;
  background-color: #fff;
  border-bottom: 1px solid #eaeaea;
}
.chatbox {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: scroll; /* 超出内容时有滚动条 */
}
.chat-content0 {
  flex-grow: 1;
}
.chat-content1 {
  display: flex;
  flex-grow: 1;
  justify-content: flex-end;
}
.chat-message {
  display: flex;
  align-items: center;
  margin: 10px;
}
.avatar {
  align-self: flex-start;
  display: flex;
  height: 40px;
  width: 40px;
  justify-content: center;
  align-items: center;
  background-color: #e6f7ff;
  border-radius: 50%;
  padding: 10px;
  margin-right: 10px;
}
.message-content {
  background-color: #f4f4f4;
  max-width: 1250px;
  text-align: left;
  padding: 10px;
  border-radius: 5px;
}
.chat-input {
  padding: 0;
  height: 350px;
}

.related-topics {
  margin-bottom: 10px;
  padding-left: 10px;
}

.related-topics h4 {
  font-size: 16px;
  color: #989898;
  margin-bottom: 5px;
  text-align: left;
}

.related-topics button {
  width: 150px;
  height: 40px;
  font-size: 16px;
  border-radius: 10px;
  color: #57a5f2;
}

.topics {
  display: flex;
  gap: 10px;
}

.divider {
  height: 1px;
  background-color: #ccc;
  margin: 20px 0;
}


.chatbox-button-group {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
  margin-bottom: 10px;
  padding-left: 10px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  padding: 0 10px;
}

.custom-textarea {
  width: 100%;
  height: 165px;
  padding: 10px;
  padding-right: 80px;
  border: 1px solid #ccc;
  border-radius: 10px;
  resize: none;
  box-sizing: border-box;
  font-size: 20px;
}


.send-button {
  position: absolute;
  right: 25px;
  top: 66%;
  transform: translateY(-50%);
  padding: 5px 10px;
  width: 100px;
  height: 40px;
  color: #fff;
  background-color: #409eff;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  margin-top: 25px;
}

.send-button:hover {
  background-color: #0056b3;
}

.vuepress-markdown-body {
  padding: 0 !important;
  background-color: #f4f4f4 !important;
}
</style>
